﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TV_Agenda_V2.Objects;

namespace TV_Agenda_V2.Controls
{
    public partial class ShowOverviewControl : UserControl
    {
        public ShowList Shows { get; set; }

        public ShowOverviewControl()
        {
            InitializeComponent();
            // Init ShowList
            Shows = new ShowList();
            Shows.ListChanged += new ListChangedEventHandler(Shows_ListChanged);

            // Init DataGridView
            dgvShowOverview.CellToolTipTextNeeded += new DataGridViewCellToolTipTextNeededEventHandler(dgvShowOverview_CellToolTipTextNeeded);
            dgvShowOverview.CellContentClick += new DataGridViewCellEventHandler(dgvShowOverview_CellContentClick);
            dgvShowOverview.CellFormatting += new DataGridViewCellFormattingEventHandler(dgvShowOverview_CellFormatting);
            dgvShowOverview.AutoGenerateColumns = false;
            dgvShowOverview.DataSource = Shows;


        }

        /// <summary>
        /// Handles the CellFormatting event of the dgvShowOverview control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DataGridViewCellFormattingEventArgs"/> instance containing the event data.</param>
        void dgvShowOverview_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if ((e.ColumnIndex == 1 || e.ColumnIndex == 2) && e.RowIndex >= 0 && e.RowIndex < Shows.Count)
            {
                Episode episode;
                if (e.ColumnIndex == 1)
                    episode = Shows[e.RowIndex].PreviousEpisode;
                else
                    episode = Shows[e.RowIndex].NextEpisode;

                if (episode != null && episode.DisplayBold)
                    dgvShowOverview[e.ColumnIndex, e.RowIndex].Style.Font = new Font(Font, FontStyle.Bold);
                else if (episode != null && !episode.DisplayBold)
                    dgvShowOverview[e.ColumnIndex, e.RowIndex].Style.Font = new Font(Font, FontStyle.Regular);

                try
                {
                    //parse the airDate to a DateTime
                    DateTime airDate = DateTime.Parse(episode.AirDate);

                    //apply the BackColor based on when the airDate was compared to Now 00:00:00
                    if (airDate > DateTime.Now.AddHours(-48) && airDate < DateTime.Now.Date)
                        dgvShowOverview[e.ColumnIndex, e.RowIndex].Style.BackColor = MainWindow.Settings.ColorLast48Hours;
                    else if (airDate >= DateTime.Now.Date && airDate <= DateTime.Now.AddHours(48))
                        dgvShowOverview[e.ColumnIndex, e.RowIndex].Style.BackColor = MainWindow.Settings.ColorNext48Hours;
                    else
                        dgvShowOverview[e.ColumnIndex, e.RowIndex].Style.BackColor = MainWindow.Settings.ColorBackground;
                }
                catch { }
            }
        }

        /// <summary>
        /// Handles the CellContentClick event of the dgvShowOverview control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DataGridViewCellEventArgs"/> instance containing the event data.</param>
        private void dgvShowOverview_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = e.RowIndex;
            int col = e.ColumnIndex;

            if (row < 0 || row >= Shows.Count)
                return;

            Show show = Shows[row];
            if (col == 0)
            {
                // Show Click
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.FileName = show.Link;
                process.Start();
            }
            else if (col == 1 || col == 2)
            {
                // Episode Click
                Episode episode;
                if (col == 1)
                    episode = show.PreviousEpisode;
                else
                    episode = show.NextEpisode;

                if (episode == null)
                    return;

                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.FileName = episode.Link;
                process.Start();

            }
            else if (col == 3)
            {
                // Button Click
                Shows.Remove(show);
            }
        }

        /// <summary>
        /// Handles the CellToolTipTextNeeded event of the dgvShowOverview control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DataGridViewCellToolTipTextNeededEventArgs"/> instance containing the event data.</param>
        private void dgvShowOverview_CellToolTipTextNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e)
        {
            int row = e.RowIndex;
            int col = e.ColumnIndex;

            if (row < 0 || row >= Shows.Count)
                return;

            Show show = Shows[row];
            StringBuilder tooltip = new StringBuilder();
            String nl = Environment.NewLine;
            if (col == 0)
            {
                // The user hovered over the Show Title
                String genres = String.Empty;
                foreach (String genre in show.Genres)
                    genres += genre + " ";

                // Create the nice tooltip
                tooltip.AppendFormat("\t{0} ({1})" + nl + nl, show.Name, show.Started);
                if (!show.Ended.Equals("0"))
                    tooltip.AppendFormat("Ended:\t\t{0}" + nl, show.Ended);
                tooltip.AppendFormat("Status:\t\t{0}" + nl, show.Status);
                tooltip.AppendFormat("Classification:\t{0}" + nl, show.Classification);
                tooltip.AppendFormat("Genres:\t\t{0}" + nl, genres);
                tooltip.AppendFormat("Air time:\t\t{0} {1} {2}" + nl, show.AirDay, show.AirTime, show.Timezone);
                tooltip.AppendFormat("Local air time:\t{0} {1}	{2}" + nl, show.LocalAirDay, show.LocalAirTime, "(Estimate)"); // TODO: display localized air time
                tooltip.AppendFormat("#Seasons:\t{0}" + nl, show.Seasons.Count);
                tooltip.AppendFormat("Runtime:\t{0}" + nl, show.Runtime);
                tooltip.AppendFormat("Origin Coutry:\t{0}" + nl, show.Country);
                tooltip.AppendFormat("Network:\t{0}" + nl, show.Network);
                tooltip.AppendFormat("Network Country:{0}" + nl, show.NetworkCountry);
                tooltip.AppendFormat("Also known as:" + nl);
                foreach (Aka aka in show.Akas)
                {
                    tooltip.AppendFormat("\t\"{0}\"", aka.Name);
                    if (!String.IsNullOrEmpty(aka.Country))
                        tooltip.AppendFormat(" ({0})", aka.Country);
                    if (!String.IsNullOrEmpty(aka.Attr))
                        tooltip.AppendFormat(" {0}", aka.Attr);
                    tooltip.Append(nl);
                }
            }
            else if (col == 1 || col == 2)
            {
                // The user hovered over an Episode
                Episode episode;
                if (col == 1)
                    episode = show.PreviousEpisode;
                else
                    episode = show.NextEpisode;

                if (episode == null)
                    return;
                // Create the nice tooltip
                DateTime airDate;
                tooltip.AppendFormat("{0} {1}" + nl, episode.ToString("%snx%seZ", ""), episode.Title);
                tooltip.AppendFormat("{0}" + nl + nl, DateTime.TryParse(episode.AirDate, out airDate) ? airDate.ToString("d") : episode.AirDate);
                tooltip.AppendFormat("Episode#:\t{0}" + nl, episode.SeasonEpisodeNumber);
                tooltip.AppendFormat("Season#:\t\t{0}" + nl, episode.SeasonNumber);
                tooltip.AppendFormat("Total Episode#:\t{0}" + nl, episode.EpisodeNumber);
                tooltip.AppendFormat("Production#:\t{0}" + nl, episode.ProdNumber);
            }
            else
                return;
            e.ToolTipText = tooltip.ToString();

        }

        /// <summary>
        /// Sorts the displayed list of shows.
        /// </summary>
        public void Sort()
        {
            //dgvShowOverview.Sort(new ShowComparer());
            dgvShowOverview.Sort(ShowInstance, ListSortDirection.Ascending);
        }

        /// <summary>
        /// Handles the ListChanged event of the Shows control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.ListChangedEventArgs"/> instance containing the event data.</param>
        private void Shows_ListChanged(object sender, ListChangedEventArgs e)
        {
            // If it isn't a Reset type re-sort the list (Reset is used when sorting the list already)
            if (e.ListChangedType != ListChangedType.Reset)
                dgvShowOverview.Sort(NextDate, ListSortDirection.Ascending);
        }

    }
}
